#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include<functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "InerAddr.hpp"
#include "ThreadPool.hpp"
using namespace std;

using task_t =function<void()>;

class MessageRoute
{
private:
    bool IsExists(const InetAddr &addr)
    {
        for (auto a : _oneline_user)
        {
            if (a == addr)
                return true;
        }
        return false;
    }

public:
    MessageRoute()
    {
    }
    void AddUser(const InetAddr &addr)
    {
        if (IsExists(addr))
            return;
        _oneline_user.push_back(addr);
    }
    void DelUser(const InetAddr &addr)
    {
        for (auto iter = _oneline_user.begin(); iter != _oneline_user.end(); iter++)
        {
            if (*iter == addr)
            {
                _oneline_user.erase(iter);
                break;
            }
        }
    }
    void RouteHelper(int sockfd, const string message)//把类内函数变成一个对象push进入线程池中
    {
        // 进行消息转发
        for (auto user : _oneline_user)
        {
            struct sockaddr_in addr = user.Addr();
            sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&addr, sizeof(addr));
        }
    }
    void Route(int sockfd, const string message, const InetAddr who)
    {
        // 新用户首次发消息，还要把自己插入到在线用户中
        AddUser(who);

        // 退出
        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
        }
        // 构建任务对象，入队列，让线程池进行转发
        task_t t=bind(&MessageRoute::RouteHelper,this,sockfd,message);
        ThreadPool<task_t>::GetInstance()->Enqueue(t);

        // 进行消息转发
        for (auto user : _oneline_user)
        {
            struct sockaddr_in addr = user.Addr();
            sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&addr, sizeof(addr));
        }
    }
    ~MessageRoute()
    {
    }

private:
    vector<InetAddr> _oneline_user;
};